<template>
  <div class="mapBox">
    <div id="viewMap"></div>
    <div class="tootl">
      <el-button
        v-if="gridType == 'zr'"
        type="success"
        size="mini"
        plain
        round
        style="margin-left: 10px"
        @click="exportDutyGrid"
        >导出网格</el-button
      >
      <el-button
        v-if="gridType == 'xz'"
        type="success"
        size="mini"
        plain
        round
        style="margin-left: 10px"
        @click="exportGrid"
        >导出网格</el-button
      >
      <el-button
        v-if="gridType == 'zrAll'"
        type="success"
        size="mini"
        plain
        round
        style="margin-left: 10px"
        @click="exportDepaGrid"
        >导出网格</el-button
      >
      <el-select
        v-model="mapStyle"
        placeholder="请选择"
        @change="styleChange"
        size="mini"
        style="width: 100px; margin-left: 10px"
      >
        <el-option label="幻影黑" value="dark"> </el-option>
        <el-option label="远山黛" value="whitesmoke"> </el-option>
        <el-option label="雅士灰" value="grey"> </el-option>
        <el-option label="靛青蓝" value="blue"> </el-option>
        <el-option label="极夜蓝" value="darkblue"> </el-option>
      </el-select>
    </div>
  </div>
</template>

<script>
import * as api from '@/api/map'
import AMapLoader from '@amap/amap-jsapi-loader'
export default {
  props: {
    // 网格编码
    adcode: {
      type: String,
      default: '',
    },
    // 层级
    level: {
      type: Number,
      default: null,
    },
    // 行政连级id
    pid: {
      type: Number,
      default: null,
    },
    // 是否显示子集
    addressSonFlag: {
      type: String,
      default: '',
    },
    // 行政连级id
    dutyId: {
      type: Number,
      default: null,
    },
    // 网格类型
    gridType: {
      type: String,
      default: '',
    },
    dutyName: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      // 地图事件
      map: null,
      // 当前编辑的网格对象
      mapStyle: 'dark',
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    // 初始化地图
    init() {
      AMapLoader.load({
        key: '30f0645cbadb0e5f302e20e86b3e627f',
        version: '2.0',
        plugins: ['AMap.Polygon', 'AMap.GeoJSON'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then(AMap => {
        this.map = new AMap.Map('viewMap', {
          mapStyle: 'amap://styles/dark',
          showBuildingBlock: true,
          showLabel: true,
          center: [113.89362474, 23.14630753],
          zoom: 14,
        })
        this.getGrid()
      })
    },
    // 获取随机颜色
    getCasualeColor() {
      let random = Math.random()
      if (random < 0.07) {
        random = Math.random()
      }
      let num = Math.floor(random * 16777215).toString(16)
      if (num.length < 6) {
        num += '1'
      }
      return '#' + num
    },
    /**
     * 初始化网格
     * @param {Object} json 地图数据
     * @returns {class}
     */
    initPolygon(json) {
      let that = this
      let geojson = new AMap.GeoJSON({
        geoJSON: json,
        getPolygon: function (geojson, lnglats) {
          let pol = new AMap.Polygon({
            path: lnglats,
            fillOpacity: geojson.properties['fill-opacity'] ?? 0.3,
            strokeColor: geojson.properties.stroke ?? that.getCasualeColor(),
            fillColor: geojson.properties.fill ?? that.getCasualeColor(),
            strokeWeight: geojson.properties['stroke-width'] ?? 2,
            zIndex: geojson.properties.zIndex ?? 0,
            id: geojson.id,
            adcode: geojson.properties.adcode,
          })
          pol.setExtData({
            rowfill: geojson.properties.fill ?? that.getCasualeColor(),
            rowfillOpac: geojson.properties['fill-opacity'] ?? 0.3,
            rowStroke: geojson.properties.stroke ?? that.getCasualeColor(),
          })
          return pol
        },
      })
      that.map.add(geojson)
      that.map.setFitView()
    },
    // 获取行政网格
    getGrid() {
      this.map.clearMap()
      let data = {
        adcode: this.adcode ?? '',
        level: this.addressSonFlag == 'son' ? this.level - 1 : this.level,
        addressPid: this.pid,
        addressSonFlag: this.addressSonFlag ?? '',
      }
      api.getAllGrid(data).then(res => {
        if (res.code == '200') {
          this.initPolygon(res.data)
        }
      })
    },
    // 获取责任网格数据
    getDutyGrid() {
      this.map.clearMap()
      let data = {
        adcode: this.adcode,
      }
      api.dutyGridDetail(data).then(res => {
        if (this.editPower && res.data[0]) {
          for (const i of res.data[0].features) {
            this.seleGrid.push(i.id)
          }
        } else if (!this.editPower && res.data[0]) {
          this.initPolygon(res.data[0])
        }
      })
    },
    // 获取全部责任网格
    getDutyAllGrid() {
      this.map.clearMap()
      api.getDutyGridJson(this.dutyId).then(res => {
        if (res.code == '200') {
          for (let i = 0, list = res.data; i < list.length; i++) {
            const item = res.data[i]
            if (item.genJson) {
              this.initPolygon(item.genJson)
            }
          }
        }
      })
    },
    // 修改地图样式
    styleChange(e) {
      this.map.setMapStyle('amap://styles/' + e)
    },
    // 导出责任网格
    exportDutyGrid() {
      let data = {
        adcode: this.adcode,
      }
      api.exportDutyGrid(data).then(res => {
        let blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        let elink = document.createElement('a')
        elink.download = `责任网格数据${this.adcode}.json`
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        document.body.removeChild(elink)
      })
    },
    // 导出部门网格
    exportDepaGrid() {
      let data = {
        departmentId: this.dutyId,
      }
      api.exportDutyGrid(data).then(res => {
        let blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        let elink = document.createElement('a')
        elink.download = `${this.dutyName}网格数据.json`
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        document.body.removeChild(elink)
      })
    },
    // 导出行政
    exportGrid() {
      let data = {
        addressPid: this.pid,
        adcode: this.adcode ?? '',
        level: this.addressSonFlag == 'son' ? this.level - 1 : this.level,
        addressSonFlag: this.addressSonFlag ?? '',
      }
      api.gridExport(data).then(res => {
        let blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        let elink = document.createElement('a')
        elink.download = '行政网格数据.json'
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        document.body.removeChild(elink)
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.mapBox {
  position: relative;
}
#viewMap {
  width: 100%;
  height: calc(100vh - 98px);
}
.tootl {
  position: absolute;
  display: block;
  right: 20px;
  top: 20px;
  border-radius: 6px;
  background-color: white;
  box-shadow: 0px 5px 5px 0px rgb(0 0 0 / 50%);
  padding: 10px;
}
</style>
